<template>
  <div class="dashboard-container">
    <!-- 添加选项卡 -->
    <el-tabs v-model="activeChart" @tab-click="handleTabChange">
      <el-tab-pane label="供应商类型分布" name="type"></el-tab-pane>
      <el-tab-pane label="供应商状态分布" name="status"></el-tab-pane>
      <el-tab-pane label="供应商等级分布" name="level"></el-tab-pane>
    </el-tabs>

    <!-- 动态显示对应图表 -->
    <div class="chart-container" v-show="activeChart === 'type'">
      <div id="typeChart" :style="{ width: '800px', height: '500px' }"></div>
    </div>
    <div class="chart-container" v-show="activeChart === 'status'">
      <div id="statusChart" :style="{ width: '800px', height: '500px' }"></div>
    </div>
    <div class="chart-container" v-show="activeChart === 'level'">
      <div id="levelChart" :style="{ width: '800px', height: '500px' }"></div>
    </div>

    <el-table
        :data="supplierPageInfo.list"
        height="950px"
        max-height="100%"
        border
        style="width: 100%">
      <el-table-column
          type="index"
          width="180" label="序号">
      </el-table-column>
      <el-table-column
          prop="supplierName"
          label="供应商名称"
          width="180">
      </el-table-column>
      <el-table-column
          prop="supplierState"
          label="供应商状态"
          width="180"
      >
        <template slot-scope="scope">
          <el-button v-if="scope.row.supplierState === '合格供应商'" type="success">{{ scope.row.supplierState }}</el-button>
          <el-button v-else-if="scope.row.supplierState === '潜在供应商'" type="danger">{{ scope.row.supplierState }}</el-button>
          <el-button v-if="scope.row.supplierState === '一级供应商'" type="success">{{ scope.row.supplierState }}</el-button>
          <el-button v-else-if="scope.row.supplierState === '二级供应商'" type="danger">{{ scope.row.supplierState }}</el-button>
          <el-button v-if="scope.row.supplierState === '三级供应商'" type="success">{{ scope.row.supplierState }}</el-button>
        </template>

      </el-table-column>
      <el-table-column
          prop="supplierType"
          label="供应商分类"
          width="180">
        <template slot-scope="scope">
          <el-button v-if="scope.row.supplierType === '零件供应商'" type="warning">{{ scope.row.supplierType }}</el-button>
          <el-button v-else-if="scope.row.supplierType === '集合供应商'" type="success">{{ scope.row.supplierType }}</el-button>
          <el-button v-else-if="scope.row.supplierType === '成品供应商'" type="danger">{{ scope.row.supplierType }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
          prop="supplierCode"
          label="供应商编码">
      </el-table-column>

      <el-table-column
          prop="supplierAddress"
          label="供应商地址"
          width="180">
      </el-table-column>
      <el-table-column
          prop="supplierSign.startTime"
          label="签约开始日期"
          width="180">
      </el-table-column>
      <el-table-column
          prop="supplierSign.endTime"
          label="签约结束日期">
      </el-table-column>
      <el-table-column
          prop="supplierSign.supplierSignDeadline"
          label="结算期限"
          width="180">
      </el-table-column>

      <el-table-column
          prop="supplierSign.creditLimit"
          label="信用额度"
          width="180">
      </el-table-column>
      <el-table-column
          prop="attachment.name"
          label="资质/证书名称">
      </el-table-column>

      <el-table-column
          prop="attachment.type"
          label="证书类型"
          width="180">
      </el-table-column>
      <el-table-column
          prop="attachment.upFileName"
          label="资质/证书附件"
          width="180">
        <template slot-scope="scope">
          <img :src="$basePath+'static/uploadImages/'+scope.row.attachment.upFileName" style="max-width: 100px">
        </template>
      </el-table-column>
      <el-table-column
          prop="contactinfo.name"
          label="联系人姓名">
      </el-table-column>
      <el-table-column
          prop="contactinfo.phone"
          label="联系人电话"
          width="180">
      </el-table-column>

      <el-table-column
          prop="contactinfo.job"
          label="联系人职位"
          width="180">
      </el-table-column>

      <el-table-column
          prop="invoiceHeader"
          label="发票抬头"
          width="180">
      </el-table-column>
      <el-table-column
          prop="taxNum"
          label="税号"
          width="180">
      </el-table-column>
      <el-table-column
          prop="taxType"
          label="税种"
          width="180">
      </el-table-column>
      <el-table-column
          prop="taxRate"
          label="税率"
          width="180">
      </el-table-column>
      <el-table-column
          prop="bank"
          label="开户银行"
          width="180">
      </el-table-column>
      <el-table-column
          prop="bankNum"
          label="银行账号"
          width="180">
      </el-table-column>
      <el-table-column
          prop="invoiceHeader"
          label="发票抬头"
          width="180">
      </el-table-column>
      <el-table-column
          prop="updateTime"
          label="更新时间"
          width="180">
        <template slot-scope="scope">
          <span>{{$dayjs(scope.row.updateTime).format('YYYY-MM-DD')}}</span>
        </template>
      </el-table-column>
    </el-table>
    <template>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </template>
  </div>
</template>

<script>
export default {
  name: "SupplierMessageSearch",
  data() {
    return {
      pageSize:5,
      total:0,
      currentPage:1,
      supplier: {},
      activeChart: 'type', // 当前激活的图表
      loading: false,
      suppliers: [],
      typeData: [],
      statusData: [], // 新增状态数据
      levelData:[],
      headers:{token:window.localStorage.getItem("token")},
      supplierPageInfo:{},
    }
  },
  mounted() {
    this.fetchSupplierData();
    this.getSuppliers(1);
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1;
      this.getSuppliers();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getSuppliers(val);
      this.currentPage = val;
    },
    getSuppliers(pageNum){
      console.log(this.supplier);
      this.$axios.post("manage/supplier/list",this.supplier,{params:{pageNum:pageNum,pageSize:this.pageSize}}).then(
          response=>{
            if (response.data) {
              const data = response.data;

              this.supplierPageInfo = data.supplierPageInfo; // 更新分页信息
              console.log(this.supplierPageInfo+"==========");
              this.total = data.supplierPageInfo.total; // 更新总数据量

              this.suppliers = data.supplierPageInfo.list; // 更新供应商列表
            } else {
              console.error("请求失败:", response.data.message);
            }
          }).catch(error => {
        console.error("请求错误:", error);
      });
    },
    async fetchSupplierData() {
      this.loading = true
      try {
        const response = await this.$axios.post("manage/supplier/allSuppliers")
        if (response.data?.suppliers) {
          this.suppliers = response.data.suppliers
          this.prepareChartData()
          this.initTypeChart()
          this.initStatusChart()
          this.initLevelChart()

        }
      } catch (error) {
        console.error("请求错误:", error)
        this.$message.error('数据加载失败')
      } finally {
        this.loading = false
      }
    },

    prepareChartData() {
      // 统计类型分布
      const typeCount = this.suppliers.reduce((acc, cur) => {
        acc[cur.supplierType] = (acc[cur.supplierType] || 0) + 1
        return acc
      }, {})
      this.typeData = Object.entries(typeCount).map(([name, value]) => ({ name, value }))

      // 统计状态分布
      const statusCount = this.suppliers.reduce((acc, cur) => {
        acc[cur.supplierState] = (acc[cur.supplierState] || 0) + 1
        return acc
      }, {})
      this.statusData = Object.entries(statusCount).map(([name, value]) => ({ name, value }))
      const levelCount = this.suppliers.reduce((acc, cur) => {
        if (cur.supplierLevel) {
          acc[cur.supplierLevel] = (acc[cur.supplierLevel] || 0) + 1
        }
        return acc
      }, {})
      this.levelData = Object.entries(levelCount).map(([name, value]) => ({ name, value }))
    },

    initTypeChart() {
      const chart = this.$echarts.init(document.getElementById('typeChart'))
      const option = this.getChartOption('供应商类型分布', this.typeData)
      chart.setOption(option)
    },

    initStatusChart() {
      const chart = this.$echarts.init(document.getElementById('statusChart'))
      const option = this.getChartOption('供应商状态分布', this.statusData)
      chart.setOption(option)
    },
    initLevelChart() {
      const chart = this.$echarts.init(document.getElementById('levelChart'))
      const option = this.getChartOption('供应商等级分布', this.levelData)
      chart.setOption(option)
    },

    // 通用图表配置
    getChartOption(title, data) {
      const colorMap = {
        '供应商类型分布': ['#e6a23c', '#67c23a', '#f56c6c'], // 橙、绿、红（对应零件/集合/成品供应商）
        '供应商状态分布': ['#67c23a', '#f56c6c', '#909399'], // 绿（合格）、红（潜在）、灰（其他状态）
        '供应商等级分布': ['#409eff', '#79bbff', '#a0cfff'] // 蓝系渐变（一级到三级）
      };
      return {
        color: colorMap[title] || '#409eff', // 默认蓝色
        title: { text: title, left: 'center' },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'center'
        },
        series: [{
          name: title,
          type: 'pie',
          radius: '50%',
          data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          itemStyle: {
            borderRadius: 6, // 增加圆角
            borderColor: '#fff',
            borderWidth: 2
          }
        }]
      }
    },


    // 切换选项卡时调整图表大小
    handleTabChange() {
      this.$nextTick(() => {
        this.$echarts.getInstanceByDom(document.getElementById('typeChart'))?.resize()
        this.$echarts.getInstanceByDom(document.getElementById('statusChart'))?.resize()
        this.$echarts.getInstanceByDom(document.getElementById('levelChart'))?.resize()
      })
    },

    stateTagType(state) {
      const types = {
        '注册': 'primary',
        '已审核': 'success',
        '禁用': 'danger',
        '待认定': 'warning'
      }
      return types[state] || 'info'
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}
.chart-container {
  margin: 20px 0;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
</style>